use common_uu::file::FileExtend;
use common_uu::IResult;
use image::{open, GenericImage, GenericImageView, ImageBuffer, Rgba, RgbaImage};
use std::fs::File;
// use std::path::Path;

/// 计算x坐标
/// hash_type [ ahash,dhash,phash ]
/// block_path 滑块
/// big_path   大图
pub fn calc_x(block_path: &str, big_path: &str) -> IResult<f64> {
    let dir_path = File::create_temporary_folder("captcha")?;

    //第一步，从滑块图中找到左上坐标，计算出x,y
    let (width, sw, sh, y, _sub_png) =
        finding_small_images(block_path.to_string(), dir_path.clone())?;

    //计算滑块的hash
    // let slider_hash = get_hash(&hash_type, sub_png.as_str());

    // 获得大图对象
    let mut big = open(big_path)?;
    let big_width = big.width();

    // 返回值
    let min_x = big_width / 2;

    //跳过滑块宽度
    let top = y;
    for x in width..big_width - sw {
        // 切割一小块图片进行逐块比对
        let clip: ImageBuffer<Rgba<u8>, Vec<u8>> = big.sub_image(x, top, sw, sh).to_image();

        // 保存每一块小图到临时文件夹
        // let mut clip_path = dir_path.clone();
        // let clip_str = &format!("/clip({}).png", x);
        // clip_path.push_str(clip_str);
        // // let clip_path = &format!("out/clip{}.png", x);
        // clip.save(clip_path.clone())?;

        for c in 0..3 {
            let mut fa = 0;
            let mut fa2 = 0;
            let mut fa3 = 0;
            let mut fa4 = 0;
            let fa_value = 205;
            let fa_value2 = 120;
            let fa_value4 = 141;

            for x in 1..55 {
                // 找下边框
                let clor = clip[(x, 52 + c)];
                if clor[0] > fa_value && clor[1] > fa_value && clor[2] > fa_value {
                    fa += 1;
                }

                // 找上边框
                let clor = clip[(x, 12 + c)];
                if clor[0] < fa_value2 && clor[1] < fa_value2 && clor[2] < fa_value2 {
                    fa2 += 1;
                }
            }

            // 找右边框
            for x in 14..55 {
                let clor = clip[(40, x)];
                if clor[0] > fa_value && clor[1] > fa_value && clor[2] > fa_value {
                    fa3 += 1;
                }
            }

            // 找左边框
            for x in 14..55 {
                let clor = clip[(0, x)];
                if clor[0] < fa_value4 && clor[1] < fa_value4 && clor[2] < fa_value4 {
                    fa4 += 1;
                }
            }

            if fa > 35 && fa2 > 15 && fa3 > 15 && fa4 > 15 {
                // println!("相似像素个数: {} 找到相似图片: {:?}", fa, &clip_path);
                return Ok(x as f64 / big_width as f64);
            }
        }

        // std::fs::remove_file(clip_path)?;
        /*
        // 计算每个小块的hash值
        let clip_hash = get_hash(&hash_type, clip_path.clone());

        // 对比滑块与切割小图的hash之间的差距, 找到差距最小的那一个即为理论上的最优解
        let dist = pihash::get_hamming_distance(slider_hash, clip_hash);
        if dist < min_dist {
            min_dist = dist;
            min_x = x;
        } else {
            // std::fs::remove_file(clip_path)?;
        }
        */
    }

    // 计算完删除文件
    std::fs::remove_dir_all(dir_path)?;

    Ok(min_x as f64 / big_width as f64)
}

/*mod opencv_use {
    use std::{env, time};

    #[cfg(feature = "opencv-4")]
    use opencv::core::AccessFlag::ACCESS_READ;
    #[cfg(not(feature = "opencv-4"))]
    use opencv::core::ACCESS_READ;
    use opencv::{
        core::{self, UMat, UMatUsageFlags},
        imgcodecs, imgproc,
        prelude::*,
        types, Result,
    };

    const ITERATIONS: usize = 100;

    #[test]
    fn run() {
        let opencl_have = core::have_opencl()?;
        println!("opencl_have: {}", opencl_have);
        if !opencl_have {
            return;
        }
    }
}*/

/// 寻找小图
fn finding_small_images(
    block_path: String,
    dir_path: String,
) -> IResult<(u32, u32, u32, u32, String)> {
    let mut block = open(block_path)?;
    //从上往下，从左往右，寻找第一个非透明像素点（左上角）
    let mut left_top = None;
    for x in 0..block.width() {
        for y in 0..block.height() {
            let pixel: Rgba<u8> = block.get_pixel(x, y);
            if pixel[3] > 30 {
                left_top = Some((x, y));
                break;
            }
        }
        if left_top.is_some() {
            break;
        }
    }
    let left_top = left_top.ok_or("left_top id none")?;
    // println!("左上角{:?}", left_top);
    let (sw, sh) = (55, 55);
    //y+4, x+6, 取宽高=(sw,sh)
    let (x, y) = (left_top.0, left_top.1 - 12);
    let sub: RgbaImage = block.sub_image(x, y, sw, sh).to_image();

    //添加40%白色半透明
    /*let mut mask: RgbaImage = RgbaImage::new(sw, sh);
    for pixel in mask.pixels_mut() {
        pixel[0] = 255;
        pixel[1] = 255;
        pixel[2] = 255;
        pixel[3] = 102;
    }*/
    // draw_image(0, 0, &mut sub, &mask);

    let p = dir_path + "/sub.png";
    sub.save(p.clone())?;
    Ok((block.width(), sw, sh, y, p))
}
